package ink.lovejinhu.sync;

/**
 * @author jinhu
 * created 2021-07-20 16:29
 */
public class SaleTicketUseSychornized {
    /**
     * 多线程实现卖票的例子
     */
    //多线程编程步骤

    /**
     * 1.创建资源类
     * 2。对资源类编写操作方法
     * **1.判断
     * **2.干活
     * **3.通知
     * 3.多线程调用
     * 防止虚假唤醒
     */

    public static void main(String[] args) {
        Ticket ticket = new Ticket(30);
        new Thread(() -> {
            for (int i = 0; i < 31; i++) {
                ticket.sale();
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "saller01").start();
        new Thread(() -> {
            for (int i = 0; i < 31; i++) {
                ticket.sale();
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "saller02").start();
        new Thread(() -> {
            for (int i = 0; i < 31; i++) {
                ticket.sale();
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "saller03").start();


    }
}

class Ticket {
    private int ticket;

    public Ticket(int ticket) {
        this.ticket = ticket;
    }

    public synchronized void sale() {

        if (ticket > 0) {
            System.out.println(Thread.currentThread().getName() + "售卖：" + "第" + ticket + "票");
            ticket--;
        }
    }
}